import React, { useState } from 'react';
import { 
  Modal, 
  Form, 
  Select, 
  Input, 
  Button, 
  Space, 
  message, 
  Typography, 
  Divider,
  QRCode,
  Tabs,
  Switch,
  DatePicker,
  InputNumber
} from 'antd';
import {
  LinkOutlined,
  QrcodeOutlined,
  ShareAltOutlined,
  CopyOutlined,
  MailOutlined,
  WechatOutlined,
  TwitterOutlined
} from '@ant-design/icons';
import dayjs from 'dayjs';

const { Text, Title } = Typography;
const { Option } = Select;
const { TabPane } = Tabs;
const { TextArea } = Input;

const ShareModal = ({ visible, onCancel, graphData }) => {
  const [form] = Form.useForm();
  const [shareUrl, setShareUrl] = useState('');
  const [activeTab, setActiveTab] = useState('link');
  const [shareSettings, setShareSettings] = useState({
    expireTime: null,
    password: '',
    allowDownload: true,
    allowEdit: false,
    viewLimit: null
  });

  // 生成分享链接
  const generateShareUrl = (settings) => {
    const baseUrl = window.location.origin;
    const graphId = graphData?.key || 'demo';
    const params = new URLSearchParams();
    
    if (settings.expireTime) {
      params.append('expire', settings.expireTime.valueOf());
    }
    if (settings.password) {
      params.append('pwd', btoa(settings.password));
    }
    if (settings.viewLimit) {
      params.append('limit', settings.viewLimit);
    }
    
    params.append('download', settings.allowDownload);
    params.append('edit', settings.allowEdit);
    
    const url = `${baseUrl}/share/graph/${graphId}?${params.toString()}`;
    setShareUrl(url);
    return url;
  };

  // 复制链接
  const copyToClipboard = async (text) => {
    try {
      await navigator.clipboard.writeText(text);
      message.success('链接已复制到剪贴板');
    } catch (err) {
      message.error('复制失败，请手动复制');
    }
  };

  // 处理分享设置变化
  const handleSettingsChange = (key, value) => {
    const newSettings = { ...shareSettings, [key]: value };
    setShareSettings(newSettings);
    generateShareUrl(newSettings);
  };

  // 生成分享文本
  const getShareText = () => {
    return `我分享了一个知识图谱：${graphData?.name}\n${graphData?.description}\n查看链接：${shareUrl}`;
  };

  // 社交媒体分享
  const shareToSocial = (platform) => {
    const text = encodeURIComponent(getShareText());
    const url = encodeURIComponent(shareUrl);
    
    const shareUrls = {
      wechat: `https://api.qrserver.com/v1/create-qr-code/?size=200x200&data=${url}`,
      weibo: `https://service.weibo.com/share/share.php?url=${url}&title=${text}`,
      twitter: `https://twitter.com/intent/tweet?text=${text}&url=${url}`,
      email: `mailto:?subject=${encodeURIComponent(graphData?.name)}&body=${text}`
    };

    if (platform === 'wechat') {
      // 微信分享显示二维码
      Modal.info({
        title: '微信分享',
        content: (
          <div style={{ textAlign: 'center', padding: '20px' }}>
            <QRCode value={shareUrl} size={200} />
            <div style={{ marginTop: '16px' }}>
              <Text type="secondary">使用微信扫描二维码分享</Text>
            </div>
          </div>
        ),
        width: 300
      });
    } else {
      window.open(shareUrls[platform], '_blank');
    }
  };

  // 发送邮件邀请
  const sendEmailInvite = async (values) => {
    try {
      // 这里应该调用后端API发送邮件
      console.log('发送邮件邀请:', values);
      message.success('邀请邮件已发送');
    } catch (error) {
      message.error('发送失败，请稍后重试');
    }
  };

  React.useEffect(() => {
    if (visible && graphData) {
      generateShareUrl(shareSettings);
    }
  }, [visible, graphData]);

  return (
    <Modal
      title={
        <div style={{ display: 'flex', alignItems: 'center' }}>
          <ShareAltOutlined style={{ marginRight: '8px', color: '#1677ff' }} />
          分享图谱 - {graphData?.name}
        </div>
      }
      open={visible}
      onCancel={onCancel}
      footer={null}
      width={600}
    >
      <Tabs activeKey={activeTab} onChange={setActiveTab}>
        {/* 链接分享 */}
        <TabPane 
          tab={
            <span>
              <LinkOutlined />
              链接分享
            </span>
          } 
          key="link"
        >
          <div style={{ padding: '16px 0' }}>
            {/* 分享设置 */}
            <div style={{ marginBottom: '24px' }}>
              <Title level={5}>分享设置</Title>
              <Space direction="vertical" style={{ width: '100%' }} size="middle">
                <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                  <Text>设置访问密码</Text>
                  <Input.Password
                    placeholder="留空表示无密码"
                    style={{ width: '200px' }}
                    value={shareSettings.password}
                    onChange={(e) => handleSettingsChange('password', e.target.value)}
                  />
                </div>
                
                <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                  <Text>有效期限</Text>
                  <DatePicker
                    showTime
                    placeholder="永久有效"
                    style={{ width: '200px' }}
                    value={shareSettings.expireTime}
                    onChange={(date) => handleSettingsChange('expireTime', date)}
                    disabledDate={(current) => current && current < dayjs().startOf('day')}
                  />
                </div>
                
                <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                  <Text>访问次数限制</Text>
                  <InputNumber
                    placeholder="无限制"
                    style={{ width: '200px' }}
                    min={1}
                    value={shareSettings.viewLimit}
                    onChange={(value) => handleSettingsChange('viewLimit', value)}
                  />
                </div>
                
                <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                  <Text>允许下载</Text>
                  <Switch
                    checked={shareSettings.allowDownload}
                    onChange={(checked) => handleSettingsChange('allowDownload', checked)}
                  />
                </div>
                
                <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                  <Text>允许编辑</Text>
                  <Switch
                    checked={shareSettings.allowEdit}
                    onChange={(checked) => handleSettingsChange('allowEdit', checked)}
                  />
                </div>
              </Space>
            </div>

            <Divider />

            {/* 分享链接 */}
            <div>
              <Title level={5}>分享链接</Title>
              <div style={{ 
                display: 'flex', 
                gap: '8px', 
                marginBottom: '16px',
                padding: '12px',
                background: '#f5f5f5',
                borderRadius: '6px'
              }}>
                <Input
                  value={shareUrl}
                  readOnly
                  style={{ flex: 1 }}
                />
                <Button 
                  icon={<CopyOutlined />} 
                  onClick={() => copyToClipboard(shareUrl)}
                >
                  复制
                </Button>
              </div>

              {/* 社交分享按钮 */}
              <Space wrap>
                <Button 
                  icon={<WechatOutlined />} 
                  onClick={() => shareToSocial('wechat')}
                  style={{ color: '#07c160' }}
                >
                  微信
                </Button>
                <Button 
                  icon={<ShareAltOutlined />} 
                  onClick={() => shareToSocial('weibo')}
                  style={{ color: '#ff8200' }}
                >
                  微博
                </Button>
                <Button 
                  icon={<TwitterOutlined />} 
                  onClick={() => shareToSocial('twitter')}
                  style={{ color: '#1da1f2' }}
                >
                  Twitter
                </Button>
                <Button 
                  icon={<MailOutlined />} 
                  onClick={() => shareToSocial('email')}
                >
                  邮件
                </Button>
              </Space>
            </div>
          </div>
        </TabPane>

        {/* 二维码分享 */}
        <TabPane 
          tab={
            <span>
              <QrcodeOutlined />
              二维码
            </span>
          } 
          key="qrcode"
        >
          <div style={{ textAlign: 'center', padding: '32px 0' }}>
            {shareUrl && (
              <>
                <QRCode value={shareUrl} size={200} />
                <div style={{ marginTop: '16px' }}>
                  <Text type="secondary">扫描二维码访问图谱</Text>
                </div>
                <div style={{ marginTop: '16px' }}>
                  <Button 
                    icon={<CopyOutlined />} 
                    onClick={() => copyToClipboard(shareUrl)}
                  >
                    复制链接
                  </Button>
                </div>
              </>
            )}
          </div>
        </TabPane>

        {/* 邮件邀请 */}
        <TabPane 
          tab={
            <span>
              <MailOutlined />
              邮件邀请
            </span>
          } 
          key="email"
        >
          <Form
            form={form}
            layout="vertical"
            onFinish={sendEmailInvite}
            style={{ padding: '16px 0' }}
          >
            <Form.Item
              name="emails"
              label="邀请邮箱"
              rules={[{ required: true, message: '请输入邮箱地址' }]}
            >
              <TextArea
                rows={3}
                placeholder="请输入邮箱地址，多个邮箱用换行分隔"
              />
            </Form.Item>
            
            <Form.Item
              name="subject"
              label="邮件主题"
              initialValue={`邀请您查看知识图谱：${graphData?.name}`}
            >
              <Input />
            </Form.Item>
            
            <Form.Item
              name="message"
              label="邀请消息"
              initialValue={`您好！\n\n我想与您分享一个知识图谱：${graphData?.name}\n\n${graphData?.description}\n\n点击链接查看：${shareUrl}`}
            >
              <TextArea rows={6} />
            </Form.Item>
            
            <Form.Item>
              <Button type="primary" htmlType="submit" block>
                发送邀请
              </Button>
            </Form.Item>
          </Form>
        </TabPane>
      </Tabs>
    </Modal>
  );
};

export default ShareModal;